package com.sx.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.SocketException;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.sx.article.entity.AttachmentEntity;
import com.sx.cms.entity.UserInfoEntity;
import com.sx.feesunit.exception.SXException;
import com.sx.rbac.entity.SysUserEntity;
import com.sx.util.SystemConfigInfo;
import com.sx.util.date.DateUtil;

@SuppressWarnings("serial")
public class BaseAction extends ActionSupport {
	private Log log = LogFactory.getLog(this.getClass());
	/**
	 * 按照编号删除附件信息
	 **/
	public boolean deleteFileInfo(String filepath) throws SXException{
		boolean flag = false;
		try {
			File myDelFile = new File(filepath);
			System.out.println(myDelFile.exists());
			if (myDelFile.exists()) {
				flag = myDelFile.delete();
			}else{
				flag = false;
			}
		} catch (Exception e) {
			// TODO: handle exception
			log.error("按照表单编号删除附件信息!",e);
		}
		return flag;
	}
	/**
	 *获取登录后的用户信息 
	 *前台注册用户
	 **/
	public UserInfoEntity getUserInfoFromSession(){
		/*UserInfoEntity userinfo = new UserInfoEntity();
		userinfo.setUserid(1);
		getSession().setAttribute("userinfo",userinfo);*/
		return (UserInfoEntity)getSession().getAttribute("userinfo");
	}
	/**
	 * 上传文件公共方法
	 * 返回上传后表单文件名称
	 * @param String root 上传路径    
	 * @param String filename 文件名称
	 * @param File file 文件
	 **/
	public AttachmentEntity getUpdateFileInfo(String root,String filename,File file) throws SXException{
		AttachmentEntity attachment = new AttachmentEntity();
		String _webrootpath = getServletContext().getContextPath();
		//获取网页的路径信息
		//获取物理路径信息
		//获取系统在计算机中的物理路径 如 C：\ncfams\webroot
		//E:\MyProject\PracticeProject\lsh\WebRoot\back//attachmentworkflow\2011-09-05day\
		String rootPath = getSession().getServletContext().getRealPath("/"+root); 
	    //根据配置的标识来创建日期文件夹 重属性文件中读取叫 dateflag 的属性
		String day = SystemConfigInfo.ARTICLE_FILE_FOLDER_CREATETIME;
		//用来创建文件夹的名称
		String sp = rootPath +"\\"+ DateUtil.getDateName(day)+day+"\\";
		//根据给定的名称 ”sp“ 创建文件夹
		MyUtils.mkDirectory(sp);
	    //获取网页中的web路径
		String webcontentpath = _webrootpath+"/"+root+"/"+DateUtil.getDateName(day)+day;
		//开始进行上传的操作
        String filevalue = MyUtils.upload(filename.replaceAll(" ", ""), sp, file);  
        //上传完成后获取文件网站全目录信息
        attachment.setFvaluename(filevalue);
        attachment.setFvaluepath(webcontentpath);
        attachment.setFdisplayname(filename);
		return attachment;
	}
	/**
	 *获取用户IP地址
	 ***/
	public String getUserIPAddress(){
		return getRequest().getRemoteAddr();
	}
	/**
	 *从session中获取一个用户 
	 ***/
	public SysUserEntity getUserFromSession(){
		return (SysUserEntity)getSession().getAttribute("sysuser");
	}
	/**
	 *获取路径系统 
	 * 
	 ***/
	public String getProjectPath(){
		//String path = getRequest().getContextPath();
		String basePath = getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+"/";
		return basePath;
	}
	
	
	
	public void outJsonString(String str) {
//		getResponse().setContentType("text/javascript;charset=UTF-8");
		getResponse().setContentType("text/html;charset=UTF-8");	
		outString(str);
	}

	/*
	 * public void outJson(Object obj) {
	 * outJsonString(JSONObject.fromObject(obj).toString()); }
	 * 
	 * public void outJsonArray(Object array) {
	 * outJsonArray(JSONArray.fromObject(array).toString()); }
	 */

	public void outString(String str) {
		try {
			getResponse().setContentType("text/html;charset=UTF-8");
			getResponse().setCharacterEncoding("utf-8");
			PrintWriter out = getResponse().getWriter();
			out.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void outXMLString(String xmlStr) {
		getResponse().setContentType("application/xml;charset=UTF-8");
		outString(xmlStr);
	}

	/**
	 * 获得request
	 * 
	 * @return
	 */
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获得response
	 * 
	 * @return
	 */
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获得session
	 * 
	 * @return
	 */
	public HttpSession getSession() {
		return getRequest().getSession();
	}
	
	/**
	 * <pre>文件上传方法</pre>
	 * @deprecated
	 * @param uploadpath   上传到服务器的路径
	 * @param filename		文件名字
	 * @param file			文件 
	 * */
	public String uploadfile(String uploadpath,String filename,File file)
	{
		String uploadDir = uploadpath;
		String path = getRealyPath(uploadDir);
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		Random random = new Random();
		int i = random.nextInt(100);
		long dateTime = new Date().getTime()+i;
		File saveFile = null;
		String houzhui = filename.substring(filename.lastIndexOf("."), filename.length());
		saveFile = new File(path +"\\" +dateTime + houzhui);
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			FileOutputStream fos = new FileOutputStream(saveFile);
			int count = 0;
			byte[] b = new byte[1024];
			while ((count = fis.read(b)) > 0) {
				fos.write(b, 0, count);
			}
			fos.close();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		String outpath = dateTime + houzhui;
		return outpath;
	}
	
	/**
	 * 下载文件
	 * realname 文件真正的名字
	 * filename 文件物理地址
	 * path     文件存在路径
	 * 
	 */
	public void downLoadAttachment(String realname,String filename,String path){
        
		String filePath = path;//getRealyPath(path+"\\"+filename);
		// System.out.println("---"+filePath+"---");
		boolean isInline = false;
		getResponse().reset();
		try {
			java.io.File f = new java.io.File(filePath);
			if (f.exists() && f.canRead()) {
				String mimetype = null;
				mimetype = getServletContext().getMimeType(filePath);
				if (mimetype == null) {
					mimetype = "application/octet-stream;charset=iso8859-1";
				}
				getResponse().setContentType(mimetype);
				String ua = getRequest().getHeader("User-Agent"); //  获取终端类型    
				if (ua == null)
					ua = "User-Agent:Mozilla/4.0(compatible; MSIE 6.0;)";
				boolean isIE = ua.toLowerCase().indexOf("msie") != -1; //  是否为 IE    
				if (isIE && !isInline) {
					mimetype = "application/x-msdownload";
				}
				//  下面我们将设法让客户端保存文件的时候显示正确的文件名, 具体就是将文件名   
				//  转换为 ISO8859-1 编码    
				String inlineType = isInline ? "inline" : "attachment"; //  是否内联附件    
				getResponse().setHeader("Content-Disposition", inlineType
						+ ";filename=\""
						+ java.net.URLEncoder.encode(filename, "UTF-8")
						+ "\"");
				getResponse().setContentLength((int) f.length()); //  设置下载内容大小    
				byte[] buffer = new byte[4096]; //  缓冲区    
				BufferedOutputStream output = null;
				BufferedInputStream input = null;
				try {
					output = new BufferedOutputStream(getResponse().getOutputStream());
					input = new BufferedInputStream(new FileInputStream(f));
					int n = (-1);
					while ((n = input.read(buffer, 0, 4096)) > -1) {
						output.write(buffer, 0, n);
						output.flush();//
					}
					getResponse().flushBuffer();
				}catch(SocketException ex){
					Log4jInit.ysulogger.error("下载文件出错 SocketException", ex);
					ex.printStackTrace();
				}catch (Exception e) {
					e.printStackTrace();
					String simplename = e.getClass().getSimpleName();
					if(!"ClientAbortException".equals(simplename)){
						Log4jInit.ysulogger.error("下载文件出错", e);
					}else{
						Log4jInit.ysulogger.error("客户端取消了文件下载！");
					}
				} //  用户可能取消了下载    
				finally {
					if (input != null){input.close();}
					if (output != null){output.close();}
				}
			}
			return;
		} catch(SocketException ex){
			Log4jInit.ysulogger.error("下载文件出错 SocketException", ex);
		}catch (Exception ex) {
			Log4jInit.ysulogger.error("下载文件出错 Exception", ex);
			ex.printStackTrace();
			return;
		}
	}
	/**
	 * 获得servlet上文路径
	 * 
	 * @return
	 */
	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}

	public String getRealyPath(String path) {
		return getServletContext().getRealPath(path);
	}
}
